//
//  GameScene.m
//  Hello
//
//  Created by apple on 12-11-11.
//  Copyright 2012年 __MyCompanyName__. All rights reserved.
//

#import "GameScene.h"


@implementation GameScene

+(id)scene{
    CCScene* scene = [CCScene node];
    CCLayer* layer = [GameScene node];
    [scene addChild:layer];
    return scene;
}

-(id)init{
    self = [super init];
    
    if (self) {
        player = [CCSprite spriteWithFile:@"alien.png"];
        [self addChild:player z:0 tag:1];
        
        CGSize screenSize = [[CCDirector sharedDirector] winSize];
        float imageHeight = player.texture.contentSize.height;
        player.position = CGPointMake(screenSize.width/2, imageHeight/2);
        
        board = [CCSprite spriteWithFile:@"board.png"];
        board.position = CGPointMake(screenSize.width - 20, screenSize.height/2);
        [self addChild:board];
        
        self.isAccelerometerEnabled = YES;
        playerVelocity.x = 1;
        playerVelocity.y = 2;
        
        [self scheduleUpdate];
    }
    
    return self;
}

-(void)dealloc{
    [super dealloc];
}

-(void)accelerometer:(UIAccelerometer *)accelerometer didAccelerate:(UIAcceleration *)acceleration{
    boardVelocity.y = acceleration.y*10.0;
    if (boardVelocity.y>100) {
        boardVelocity.y = 100;
    }
    if (boardVelocity.y<-100) {
        boardVelocity.y = -100;
    }
}

-(void)update:(ccTime)delta{
    CGSize screenSize = [[CCDirector sharedDirector] winSize];
    CGPoint pos = player.position;
    pos.x += playerVelocity.x;
    pos.y += playerVelocity.y;
    
    float width = player.textureRect.size.width/2;
    float height = player.textureRect.size.height/2;
    if ((pos.x==width)||(pos.x==screenSize.width-width)) {
        playerVelocity.x = - playerVelocity.x;
    }
    CGFloat distance = board.position.x-pos.x;
    CGFloat bang     = (player.textureRect.size.width+board.textureRect.size.width)/2;
    if (ABS(distance-bang)<1){
        if (ABS(pos.y-board.position.y)<(board.textureRect.size.height+player.textureRect.size.height)/2) {
            playerVelocity.x = -playerVelocity.x;
        }
    }
    if ((pos.y==height)||(pos.y==screenSize.height-height)) {
        playerVelocity.y = - playerVelocity.y;
    }
    player.position = pos;
    
    CGPoint boardPos = board.position;
    boardPos.x += boardVelocity.x;
    boardPos.y += boardVelocity.y;
    
    CGFloat boardHeight = board.textureRect.size.height/2;

    if (boardPos.y>screenSize.height-boardHeight) {
        boardPos.y=screenSize.height-boardHeight;
    }
    if (boardPos.y<boardHeight) {
        boardPos.y=boardHeight;
    }
    board.position = boardPos;
    
    if (screenSize.width-width-pos.x<10) {
        [self pauseSchedulerAndActions];
        UIAlertView* alert = [[UIAlertView alloc] initWithTitle:@"您输了" message:@"你输了" delegate:self cancelButtonTitle:@"最近状态不佳" otherButtonTitles:nil, nil];
        [alert show];
        [alert release];
    }
}

@end
